package cn.com.captureNetPacket.util;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.com.captureNetPacket.CaptureNetPacketService;
import cn.com.captureNetPacket.model.ConfigData;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Tools {
	private static  ObjectMapper obojMapper= new ObjectMapper();
	
	public static DateTimeFormatter dfFull=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
	  // 创建 Pattern 对象  解析sip用户的正则表达式
	public final static Pattern sipUserPattern = Pattern.compile("sip:(.*?)@");
	
	  public static String macAsString(final byte[] mac) {  // 此方法格式化mac地址
		    final StringBuilder buf = new StringBuilder();  
		    if(mac==null ) {
		    	buf.append("no mac");  
		    	return buf.toString();
		    }
		    for (byte b : mac) { 
		      if (buf.length() != 0) {  
		        buf.append(':');  
		      }  
		      if (b >= 0 && b < 16) {  
		        buf.append('0');  
		      }  
		      buf.append(Integer.toHexString((b < 0) ? b + 256 : b).toUpperCase());  
		    }  

		    return buf.toString();  
		  }
	  //int占两个字节的，转换成16进制的字符，然后转数字
	  public static int readInt(final byte[] bs) {
		  final StringBuilder buf = new StringBuilder();  
		  for (byte b : bs) {
			  if (b >= 0 && b < 16) {  
			        buf.append('0');  
			      }  
			      buf.append(Integer.toHexString((b < 0) ? b + 256 : b).toUpperCase());
			      if(buf.length()>2)break;
		}
		  
		return  Integer.valueOf(buf.toString(), 16);  
		  
	  }
	  
	  
	  //
	  public static boolean isTimeOutPacket(LocalDateTime lastDateTime) {
		  if(lastDateTime.plus(CaptureNetPacketService.getAppConfig().getTimeOutPacket(), ChronoUnit.MILLIS).isBefore(LocalDateTime.now()))
			  return true;
		  else 
			  return false;
	  }



	// 语音等连续包超时
	public static boolean isTimeOutRtpPacket(LocalDateTime lastDateTime) {
		if(lastDateTime.plus(CaptureNetPacketService.getAppConfig().getRtpPacketTimeOut(), ChronoUnit.MILLIS).isBefore(LocalDateTime.now()))
			return true;
		else
			return false;
	}
	  // 心跳包超时，应用层的信令超时
	  public static boolean isHeartTimeOutPacket(LocalDateTime lastDateTime) {
		  if(lastDateTime.plus(CaptureNetPacketService.hertTimeOutPacket, ChronoUnit.MILLIS).isBefore(LocalDateTime.now()))
			  return true;
		  else 
			  return false;
	  }
	  // 读取数据的参数配置
	  public static ConfigData readConfig() {
		  ConfigData configData=new ConfigData();
		  String name="",value="";
		  for (Field field : ConfigData.class.getDeclaredFields()) {
				 
				 try {
					 name="ConfigData:"+CaptureNetPacketService.getClusterServId()+":"+field.getName();
					 try {
					   value=RedisConfig.getValue(name);
					 }catch (Exception e) {
						 value=null;
					}
					   log.info(" fieldName: {}, fieldType: {} ,value: {}",field.getName(),field.getType(),value);
					   if(value==null) {
						   log.warn(" fieldName: {}, fieldType: {} , 没有获取这个字段的值,请执行配置",field.getName(),field.getType());
					   }
					field.setAccessible(true);
					if(field.getType().equals(String.class)) {
						field.set(configData,value);
					}else if(field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) {
						field.set(configData,Boolean.parseBoolean(value));
					}else if(field.getType().equals(int.class)||field.getType().equals(Integer.class)) {
						field.set(configData,Integer.parseInt(value));
					}else if(field.getType().equals(long.class) || field.getType().equals(Long.class)) {
						field.set(configData,Long.parseLong(value));
					}else if(field.getType().equals(float.class) || field.getType().equals(Float.class)) {
						field.set(configData,Float.parseFloat(value));
					}else if(field.getType().equals(double.class) ||field.getType().equals(Double.class)) {
						field.set(configData,Double.parseDouble(value));
					}else if(field.getType().equals(short.class)||field.getType().equals(Short.class)) {
						field.set(configData,Short.parseShort(value));
					}else if(field.getType().equals(List.class)) {
						field.set(configData,Arrays.asList(value.split(",")));
					}else if(field.getType().equals(ArrayList.class)) {
						field.set(configData,new ArrayList<>(Arrays.asList(value.split(","))));
					}else if(field.getType().equals(String[].class)) {
						field.set(configData,value.split(","));
					}else if(field.getType().equals(HashSet.class) || field.getType().equals(Set.class)) {
						field.set(configData,new HashSet<>(Arrays.asList(value.split(","))));
					}
					 
				}catch (SecurityException e) {
					log.warn("getField faile Name {} ,value: {}SecurityException",field.getName(),value,e);
				}catch (Exception e) {
					log.warn("getField faile Name {} ,value: {}Exception",field.getName(),value,e);
				}
			}
		  log.info("---------->>>configData :{}",configData);
		  
			  return configData;
	  }
	  
	  /**
	   * 
	  	* <strong>Title: <strong>
	  	* <p>Description: 合并两个数组为新的数组，数组2添加在数组1后面<p>
	  	* <p>Company: </p> 
	  	*<strong>Copyright:</strong> Copyright (c) 2019
	  	* @version: 1.0
	  	* @author  ASUS:augustWei
	  	* @date  2020 上午12:38:41
	  	* @param byte1
	  	* @param byte2
	  	* @return
	   */
	  public static byte[] byteMerger(byte[] byte1, byte[] byte2){
	        byte[] bt3 = new byte[byte1.length+byte2.length];  
	        System.arraycopy(byte1, 0, bt3, 0, byte1.length);  
	        System.arraycopy(byte2, 0, bt3, byte1.length, byte2.length);  
	        return bt3;  
	    } 
	  /**
	   * 
	  	* <strong>Title: <strong>
	  	* <p>Description: 一维数组转为二维数组，剩余部分，copy过去<p>
	  	* <p>Company: </p> 
	  	*<strong>Copyright:</strong> Copyright (c) 2019
	  	* @version: 1.0
	  	* @author  ASUS:augustWei
	  	* @date  2020 上午12:38:41
	  	* @return
	   */
	  public static byte[][] oneDimensional2TwoDimensional(byte[] arraysInt,int rate,int groupCount) {
		  byte[][] secArrays=new byte[groupCount][rate];
			for (int i = 0; i < secArrays.length; i++) {
				 for (int j = 0; j < rate; j++) {
					 secArrays[i][j]=arraysInt[(i)*rate+j];
				}
			}
			return secArrays;
		}
	  
	  public static String  getjsonString(Object obj) {
		  try {
			return obojMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			 return null;
		}
	  }
	  /**
	   * 获取sip号码
	   * @param sipLine
	   * @return
	   */
	  public static String  getSipUserNumber(String sipLine) {
		  try {
			  // 现在创建 matcher 对象
		      Matcher matcher = sipUserPattern.matcher(sipLine);
		      if(matcher.find()) {
		    	  return matcher.group(1);
		    	  }
		      else return sipLine;
		  } catch (Exception e) {
			 log.error("----------------------------------->>>>{}",sipLine,e);
			  return sipLine;
		  }
	  }
	  
	  
	  
	  
	  
	  
	  
	  
}
